<script setup>

import axios from 'axios'
import {ref,onMounted,watch } from 'vue';
import {ElMessage,ElMessageBox} from 'element-plus'
import qs, {stringify} from 'qs'

const input = ref('')
const value=ref();

//分页
// const tableData = ref([]); // 当前页的数据列表
const total = ref(0); // 总记录数
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示的记录数

function fetchData(page) {
    // 发送请求到后端获取数据
        axios({
            method:"post",
            url: 'http://localhost:8080/admin/users',
            data: {"currentpage":page},
            transformRequest: [ function(data){
                return qs.stringify(data)  //使用Qs将请求参数序列化
            }],
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'  //必须设置传输方式
            }
        }).then(response => {
            tableData.value = [];
            total.value = response.data.total;
            // currentPage.value = response.data.pageNum;
            response.data.list.forEach(item => {
                tableData.value.push(item);
            });
            // tableData.value = response.data.list;
        })
        .catch(error => {
            console.error("Error fetching data:", error);
        });
};

function handlePageChange(newPage){

    currentPage.value = newPage;
    fetchData(newPage);
};



//表格数据
const tableData =ref([])
function getAll(){
  axios({
    method:"get",
    url:"http://localhost:8080/admin/users",
  }).then((response)=>{
    tableData.value=response.data
    console.log(response.data)
  }).catch((error)=>{
    console.log(error);
  })
}
fetchData(1); // 初始加载第一页数据


// 角色选项
const options = ref(

    {
    rid:'',
    rname:'',
});
function getRoleName(rid) {
    switch (rid) {
        case 1:
            return '管理员';
        case 2:
            return '用户';
        default:
            return '商家';
    }
}
function getRoles() {
  axios.get('http://localhost:8080/system/getrole',options.value).then((response) => {
    options.value = response.data; // 假设返回的数据已经是选项数组
  }).catch((error) => {
    console.error('获取角色数据失败:', error);
  });
}

// 性别选项
const genderOptions = ref([

  {
    label:'男',
    value:'男'
  },
  {
    label:'女',
    value:'女'
  },
]);

// 用户状态选项
const soptions = ref([

  {
    label:'正常',
    value:'正常'
  },
  {
    label:'已注销',
    value:'已注销'
  },

]);


// 同意用户
function approveUser(uid) {
  ElMessageBox.confirm('确定要同意这个用户的审核请求吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    axios({
      method: 'post',
      url: `http://localhost:8080/admin/addMerchant`,
      data: { uid, status: '正常', identity: '商家' }
    }).then((response) => {
      if (response.data === 1) {
        ElMessage({
          type: 'success',
          message: '同意成功'
        });
        fetchData(1); // 初始加载第一页数据
      } else {
        ElMessage({
          type: 'error',
          message: '同意失败'
        });
      }
    }).catch(() => {
      ElMessage({
        type: 'error',
        message: '同意请求失败'
      });
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消操作'
    });
  });
}

// 拒绝用户
function rejectUser(uid) {
  ElMessageBox.confirm('确定要拒绝这个用户的审核请求吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    axios({
      method: 'post',
      url: `http://localhost:8080/admin/delMerchant`,
      data: { uid, status: '正常', identity: '用户' }
    }).then((response) => {
      if (response.data === 1) {
        ElMessage({
          type: 'success',
          message: '拒绝成功'
        });
        fetchData(1); // 初始加载第一页数据
      } else {
        ElMessage({
          type: 'error',
          message: '拒绝失败'
        });
      }
    }).catch(() => {
      ElMessage({
        type: 'error',
        message: '拒绝请求失败'
      });
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消操作'
    });
  });
}


// 搜索参数
const searchParams = ref({
  loginname: '',
  sex:'',
  minAmount: '',
  maxAmount: '',
  rid: '',
  ustatus: '',
  currentPage:'',
});

// 处理搜索事件
function handleSearch() {
    searchParams.value.currentPage=currentPage.value;
    const formData = new URLSearchParams(searchParams.value);
    axios({
        url:"http://localhost:8080/admin/userlist",
        method:"post",
        data:searchParams.value,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded' // 设置正确的请求头
        }
    }).then((response) => {
        tableData.value = response.data.list; // 假设返回的数据已经是选项数组
    }).catch((error) => {
        console.error('查询失败:', error);
        ElMessage.error('查询失败');

    });



}


//添加客户
let dialogVisible=ref(false)
let form=ref({
  loginname:'',
  uname:'',
  pwd:'',
  sex:'',
  email:'',
  tel:'',
  rid:'',
  ustatus:'',
  uaddress:'',
  province: '',
  city: '',
  county: '',
})
// 取消按钮的点击事件
function cancelAdd() {
  // 清空表单
  form.value = {
    loginname: '',
    uname: '',
    pwd: '',
    sex: '',
    email: '',
    tel: '',
    rid: '',
    ustatus: '',
    uaddress: '',
    province: '',
    city: '',
    county: '',
  };
  dialogVisible.value = false;
}
function  addUser(){
  form.value = {
    loginname: '',
    uname: '',
    pwd: '',
    sex: '',
    email: '',
    tel: '',
    rid: '',
    ustatus: '',
    uaddress: '',
    province: '',
    city: '',
    county: '',
  };
  dialogVisible.value = true;
}
function addCustom(){
  dialogVisible.value=false;
    const formData = new URLSearchParams(form.value);
  axios({
    url:"http://localhost:8080/admin/addUser",
    method:"post",
    data:formData,
      headers: {
          'Content-Type': 'application/x-www-form-urlencoded' // 设置正确的请求头
      }
  }).then((response)=>{
    if(response.data===1){
      // error
      ElMessage({
        type: 'success',
        message: '添加成功',
        showClose: true
      });
        fetchData(1); // 初始加载第一页数据
    }else{
      // success

      ElMessage({
        type: 'error',
        message: '用户名已存在',
        showClose: true
      });
        fetchData(1); // 初始加载第一页数据
    }
  })
}
// 检查表单是否有效
const isFormValid = ref(false);
watch(
    () => [form.value.loginname, form.value.pwd],
    ([loginname, pwd]) => {
      isFormValid.value = loginname.trim() !== '' && pwd.trim() !== '';
    },
    { immediate: true }
);

// 地址选项
const provinceOptions = ref([
]);
const cityOptions = ref([

]);
const countyOptions = ref([

]);

function getProvinces() {
  cityOptions.value = [];
  countyOptions.value = [];
  form.city = '';
  form.county = '';
  axios.get('http://localhost:8080/admin/se1').then((response) => {
    provinceOptions.value = response.data.map(item => ({
      label: item.name, // 假设后端返回的省份名称字段为 name
      value: item.id // 假设后端返回的省份 ID 字段为 id
    }));
    // 清空城市和县选项，并重置表单中的地址选项

  }).catch((error) => {
    console.error('获取省份数据失败:', error);
    ElMessage.error('获取省份数据失败');
  });
}

function getCities(id) {
  cityOptions.value = [];
  countyOptions.value = [];
  form.value.city = '';
  form.value.county = '';
  axios.get(`http://localhost:8080/admin/se2?id=${id}`).then((response) => {
    cityOptions.value = response.data.map(item => ({
      label: item.name, // 假设后端返回的城市名称字段为 name
      value: item.id // 假设后端返回的城市 ID 字段为 id
    }));
    // 清空县选项，并重置表单中的地址选项

  }).catch((error) => {
    console.error('获取城市数据失败:', error);
    ElMessage.error('获取城市数据失败');

  });
}
function getCounties(id) {
  countyOptions.value = [];
  form.value.county = '';
  axios.get(`http://localhost:8080/admin/se2?id=${id}`).then((response) => {

    countyOptions.value = response.data.map(item => ({
      label: item.name, // 假设后端返回的县名称字段为 name
      value: item.id // 假设后端返回的县 ID 字段为 id
    }));
  }).catch((error) => {
    console.error('获取县数据失败:', error);
    ElMessage.error('获取县数据失败');
  });
}


onMounted(() => {
  getRoles();
  getProvinces();
  fetchData(1); // 初始加载第一页数据
});

//批量删除
const selectedRows = ref([]);
function handleSelectionChange(val) {
  selectedRows.value = val;
}
function batchDelete() {
  if (selectedRows.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的项'
    });
    return;
  }
  ElMessageBox.confirm('确定要删除选中的项吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const uids = selectedRows.value.map(row => row.uid);
    axios.post('http://localhost:8080/admin/bulkUserTruee', { uids: uids }, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      transformRequest: [function (data) {
        return qs.stringify(data);
      }]
    }).then((response) => {
      if (response.data === 1) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        });
        getAll(); // 重新获取数据
      } else {
        ElMessage({
          type: 'error',
          message: '删除失败'
        });
      }
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      });
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除'
    });
  });
}


//删除客户
function deleteCustom(uid){
  ElMessageBox.confirm(
      "请确定是否要删除","提示",
      {   confirmButtonText:"确定",cancelButtonText:"取消",type:'warning' }
  ).then(()=>{
    axios({
      method:"post",
      url:"http://localhost:8080/admin/delUser",
      data:{"uid":uid},
      transformRequest: [ function(data){
        return qs.stringify(data)  //使用Qs将请求参数序列化
      }],
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'  //必须设置传输方式
      }

    }).then((response)=>{
      if(response.data===1){
          fetchData(1); // 初始加载第一页数据
        ElMessage({ type:'success',  message:'删除成功'  })
      }else{
        ElMessage({ type:'error', message:response.data  })
      }
    })
  }).catch(()=>{
    ElMessage({
      type:'info',
      message:"取消删除"
    })
  })
}
let dialogEdit = ref(false);
let formEdit = ref(
    {
  pwd: '',
  ustatus: '',
})

//查看
function getaCustom(uid){
  dialogEdit.value=true;
  alert(uid)
  axios({
    method:"post",
    url:`http://localhost:8080/admin/updateUser`,
    data:{"uid":uid},
    transformRequest: [ function(data){
      return qs.stringify(data)  //使用Qs将请求参数序列化
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'  //必须设置传输方式
    }
  }).then((response)=>{
    formEdit.value=response.data;
  })
}
//获取一条数据
function getOneCustom(uid){
  dialogEdit.value=true;
  alert(uid)
  axios({
    method:"post",
    url:`http://localhost:8080/admin/upUser`,
    data:{"uid":uid},
    transformRequest: [ function(data){
      return qs.stringify(data)  //使用Qs将请求参数序列化
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'  //必须设置传输方式
    }
  }).then((response)=>{
      formEdit.value=response.data;
  })
}

//修改
function updateCustom(){
  dialogEdit.value=false;
  axios({
    url:"http://localhost:8080/admin/updateUser",
    method:"post",
    data:formEdit.value,
  }).then((response)=>{
    if(response.data===1){
        fetchData(1); // 初始加载第一页数据
      ElMessage({
        message: '修改成功',
        type: 'success',
        showClose: true,

      })
    }else{
        fetchData(1); // 初始加载第一页数据
          ElMessage({
            message: '修改失败',
            type: 'error',
            showClose: true,
          })
      }
  })
}

</script>

<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="max-width: 100%">

      <!-- 查询 -->
      <el-row>
        <el-col :span="4">
          <el-select v-model="searchParams.rid"  clearable placeholder="请选择身份" style="width: 180px">
            <el-option v-for="item in options" :key="item.value" :label="item.rname" :value="item.rid"/>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchParams.ustatus" clearable placeholder="请选择用户状态" style="width: 180px">
            <el-option v-for="item in soptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchParams.sex"  clearable placeholder="请选择性别" style="width: 180px">
            <el-option v-for="item in genderOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-input v-model="searchParams.minAmount" placeholder="最低金额" style="width: 180px"/>
        </el-col>
        <el-col :span="4">
          <el-input v-model="searchParams.maxAmount" placeholder="最高金额" style="width: 180px"/>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="handleSearch" class="searchbtn">
            <el-icon class="icon-search"><Search /></el-icon>查询
          </el-button>
        </el-col>
        <!-- 添加按钮 -->
        <el-col :span="2">
          <el-button type="primary" @click="addUser()" style="margin-left: 5px">
            <el-icon><CirclePlus /></el-icon>添加用户
          </el-button>
        </el-col>
        <el-divider />
      </el-row>


      <!-- 表格 -->
      <el-row>
        <el-table :data="tableData" border style="width: 100%" >
          <el-table-column prop="uimage" label="头像" width="100" align="center">
            <template #default="scope">
              <el-image style="width: 100px; height: 100px; border-radius: 50%; object-fit: cover;" :src="scope.row.uimage"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="uid" label="用户" width="50" align="center" />
          <el-table-column prop="loginname" label="用户账号" width="100" align="center" />
          <el-table-column prop="uname" label="用户姓名" width="100" align="center" />
          <el-table-column prop="pwd" label="密码" width="100" align="center" />
          <el-table-column prop="sex" label="性别" width="50" align="center" />
          <el-table-column prop="email" label="邮箱" width="100" align="center" />
          <el-table-column prop="income" label="交易总额" width="100" align="center" />
          <el-table-column prop="uaddress" label="地址" width="200" align="center" />
          <el-table-column prop="tel" label="联系电话" width="100" align="center" />
            <el-table-column prop="rid" label="用户身份" width="50" align="center" >
                <template #default="scope">
                    {{ getRoleName(scope.row.rid) }}
                </template>
            </el-table-column>
          <el-table-column prop="ustatus" label="用户状态" width="100" align="center" >
            <template #default="scope">
              <el-tag :type="scope.row.ustatus==='正常'?'success':'warning'">{{ scope.row.ustatus }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" style="width: 180px" align="center" >
            <template #default="scope">
              <el-tooltip content="编辑" placement="bottom" effect="light">
                <el-button text  @click="getOneCustom(scope.row.uid)">
                  <el-icon ><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <br>
              <el-tooltip content="删除" placement="bottom" effect="light">
                <el-button text  @click="deleteCustom(scope.row.uid)">
                  <el-icon ><Delete /></el-icon>
                </el-button>
              </el-tooltip>
              <br>
              <el-tooltip effect="dark" content="同意" v-if="scope.row.ustatus === '审核中'">
                <el-button type="success" @click="approveUser(scope.row.uid)">
                  <el-icon>同意</el-icon>
                </el-button>
              </el-tooltip>
              <br>
              <el-tooltip effect="dark" content="拒绝" v-if="scope.row.ustatus === '审核中'">
                <el-button style="margin-top: 5px" type="error" @click="rejectUser(scope.row.uid)">
                  <el-icon >拒绝</el-icon>
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
<!--  分页-->
          <el-pagination
                  size="small"
                  background
                  layout="prev, pager, next"
                  :total="total"
                  v-model:currentPage="currentPage"
                  @current-change="handlePageChange"
                  class="mt-4"
          />
      </el-row>
    </el-card>



    <!-- 添加客户的布局 -->
    <el-dialog v-model="dialogVisible" title="添加客户" width="750">
      <el-form :model="form" style="max-width: 700px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 账户名的表单验证 -->
              <el-form-item label="账户名" prop="loginname" :rules="[{ required: true, message: '账户名不能为空', trigger: 'blur' }]">
                <el-input v-model="form.loginname" placeholder="请填写账户名" />
              </el-form-item>
            </el-col>
            <!-- 密码的表单验证 -->
            <el-col :span="12">
              <el-form-item label="密码" prop="pwd" :rules="[{ required: true, message: '密码不能为空', trigger: 'blur' }]">
                <el-input v-model="form.pwd" placeholder="请填写密码" />
              </el-form-item>
            </el-col>
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input v-model="form.uname" placeholder="请填写姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="searchParams.sex" placeholder="请填写用户性别" >
                <el-option v-for="item in genderOptions" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input v-model="form.email" placeholder="请填写邮箱"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话">
              <el-input v-model="form.tel" placeholder="请填写电话"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户身份">
                <el-select v-model="searchParams.rid" placeholder="请填写用户身份" >
                  <el-option v-for="item in options" :key="item.value" :label="item.rname" :value="item.rid"/>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户状态">
              <el-select v-model="searchParams.ustatus" placeholder="请选择用户状态" >
                <el-option v-for="item in soptions" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址">
          <el-col :span="6">
            <el-form-item label="省份">
              <el-select v-model="form.province" placeholder="请选择省份" @change="getCities(form.province)" style="margin-right: 10px">
                <el-option v-for="item in provinceOptions" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="城市">
              <el-select v-model="form.city"    placeholder="请选择城市" @change="getCounties(form.city)" style="margin-right: 10px">
                <el-option v-for="item in cityOptions" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="县">
              <el-select v-model="form.county" placeholder="请选择县">
                <el-option v-for="item in countyOptions" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
           </el-form-item>
          </el-col>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button  @click="cancelAdd">取消</el-button>
          <el-button type="primary" @click="addCustom" :disabled="!isFormValid">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑客户的布局 -->
    <el-dialog v-model="dialogEdit" title="编辑客户" width="750">
      <el-form :model="formEdit" style="max-width: 700px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码">
              <el-input v-model="formEdit.pwd" placeholder="请填写密码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户身份">
              <el-select v-model="formEdit.rid" placeholder="请填写用户身份" >
                <el-option v-for="item in options" :key="item.value" :label="item.rname" :value="item.rid"/>
              </el-select>

            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogEdit = false">取消</el-button>
          <el-button type="primary" @click="updateCustom">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>

.el-breadcrumb{
  margin-bottom: 20px;
}

.searchbtn{
  float: right;
}

.icon-search{
  margin-right: 10px;
}

.el-table{
  margin-top: 20px;
}
</style>